import React, { useEffect, useState } from "react";
import { Layout, Menu } from "antd";
import "./index.css";
import { withRouter } from "react-router-dom";
import { UserOutlined } from "@ant-design/icons";
import axios from "axios";
const { Sider } = Layout;
const { SubMenu } = Menu;

//模拟数组结构
/* const menuList = [
  {
    key: "/home",
    title: "首页",
    icon: <UserOutlined />,
  },
  {
    key: "/user-manage",
    title: "用户管理",
    icon: <UserOutlined />,
    children: [
      {
        key: "/user-manage/list",
        title: "用户列表",
        icon: <UserOutlined />,
      },
    ],
  },
  {
    key: "/right-manage",
    title: "权限管理",
    icon: <UserOutlined />,
    children: [
      {
        key: "/right-manage/role/list",
        title: "角色列表",
        icon: <UserOutlined />,
      },
      {
        key: "/right-manage/right/list",
        title: "权限列表",
        icon: <UserOutlined />,
      },
    ],
  },
]; */

function SideMenu(props) {
  // 这里面需要传入一个请求返回的数据作为新的参数。因为menu本来就是数组，所以我们定义默认为空数组
  const [menu, setMenu] = useState([]);
  // console.log('props',props.location.pathname);
  // 改变state参数
  useEffect(() => {
    axios
      .get("http://localhost:5000/rights?_embed=children")
      .then((res) => {
        setMenu(res.data);
      })
      .catch((err) => {
        console.log("err", err);
      });
  }, []);

  const checkPermission = (data) => {
    return data.pagepermisson;
  };

  const iconObj={
    "/home":<UserOutlined />,
    "/user-manage":<UserOutlined />,
    "/user-manage/list":<UserOutlined />,
    "/right-manage/role/list":<UserOutlined />,
    "/right-manage/right/list":<UserOutlined />,
  }

  const renderMenu = (menuList) => {
    return menuList.map((item) => {
      // if (item.children && item.children.length&&checkPermission(item)) {
      if (item.children?.length && checkPermission(item)) {
        return (
          <SubMenu key={item.key} icon={iconObj[item.key]} title={item.title}>
            {renderMenu(item.children)}
          </SubMenu>
        );
      }
      if (checkPermission(item)) {
        return (
          <Menu.Item
            key={item.key}
            icon={iconObj[item.key]}
            onClick={() => {
              //  console.log(props)
              props.history.push(item.key);
            }}>
            {item.title}
          </Menu.Item>
        );
      }
    });
  };

  // 根据当前的url访问地址获取上一级的
const getOpenKeys=(path)=>{
  // /user-manage/list
  let dadPath='/'+path.split('/')[1]
  return dadPath
}

  return (
    <Sider trigger={null} collapsible collapsed={false}>
      <div className="logo">全球新闻发布管理系统</div>
      <Menu theme="dark" mode="inline" defaultSelectedKeys={[props.location.pathname]} defaultOpenKeys={[getOpenKeys(props.location.pathname)]}>
        {renderMenu(menu)}
      </Menu>
    </Sider>
  );
}
export default withRouter(SideMenu);
